package com.szgd.util;


import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import org.apache.log4j.Logger;

import java.io.File;

public class DocConventer {

	static final int wdDoNotSaveChanges = 0;// 不保存待定的更改。
	static final int wdFormatPDF = 17;// PDF 格式
	private static Logger logger = Logger.getLogger(DocConventer.class);
	
	public static void main(String[] args) {
		DocConventer.word2PDF("E:/test/技术侦查证据材料移送清单.doc", "E:/test/transfered.pdf");
//		DocConventer.word_Print("E:/test/技术侦查证据材料移送清单.doc");
//		DocConventer.wordPrint("E:/test/技术侦查证据材料移送清单.doc");
	}
/*	
 * public static int office2PDF(String sourceFile, String destFile) {
		try {
			File inputFile = new File(sourceFile);
			if (!inputFile.exists()) {
				return -1;// 找不到源文件, 则返回-1
			}
			// 如果目标路径不存在, 则新建该路径
			File outputFile = new File(destFile);
			if (!outputFile.getParentFile().exists()) {
				outputFile.getParentFile().mkdirs();
			}

			String OpenOffice_HOME = "C:\\Program Files\\OpenOffice.org 3";// 这里是OpenOffice的安装目录,
																			// 在我的项目中,为了便于拓展接口,没有直接写成这个样子,但是这样是绝对没问题的
			// 如果从文件中读取的URL地址最后一个字符不是 '\'，则添加'\'
			if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '\\') {
				OpenOffice_HOME += "\\";
			}
			// 启动OpenOffice的服务
			String command = OpenOffice_HOME
					+ "program\\soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";
			Process pro = Runtime.getRuntime().exec(command);
			// connect to an OpenOffice.org instance running on port 8100
			OpenOfficeConnection connection = new SocketOpenOfficeConnection(
					"127.0.0.1", 8100);
			connection.connect();

			// convert
			DocumentConverter converter = new OpenOfficeDocumentConverter(
					connection);
			converter.convert(inputFile, outputFile);

			// close the connection
			connection.disconnect();
			// 关闭OpenOffice服务的进程
			pro.destroy();

			return 0;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return -1;
		} catch (ConnectException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return 1;
	}
	*/

	/**
	 * 通过Jacob插件调用Word程序，将Word文档转换成PDF文档
	 * @param sourceFile Word源文件，全路径
	 * @param destFile PDF目标输出文件，全路径
	 */
	public static void word2PDF(String sourceFile, String destFile) {
		logger.info("启动Word...");
		long start = System.currentTimeMillis();
		ActiveXComponent app = null;
		try {
			app = new ActiveXComponent("Word.Application");
			app.setProperty("Visible", false);

			Dispatch docs = app.getProperty("Documents").toDispatch();
			logger.info("打开文档..." + sourceFile);
			Dispatch doc = Dispatch.call(docs,//
					"Open", //
					sourceFile,// FileName
					false,// ConfirmConversions
					true // ReadOnly
					).toDispatch();

			logger.info("转换文档到PDF..." + destFile);
			File tofile = new File(destFile);
			if (tofile.exists()) {
				tofile.delete();
			}
			Dispatch.call(doc,//
					"SaveAs", //
					destFile, // FileName
					wdFormatPDF);
			
			Dispatch.call(doc, "Close", false);
			long end = System.currentTimeMillis();
			logger.info("转换完成..用时：" + (end - start) + "ms.");
			//删除临时doc文档
			File docFile = new File(sourceFile);
			if(docFile != null ){
				docFile.delete();
				logger.info("已删除临时word文件"+sourceFile);
			}
			
		} catch (Exception e) {
			System.out.println("========Error:文档转换失败：" + e.getMessage());
			logger.error("========Error:文档转换失败："+e.getMessage());
			e.printStackTrace();
		} finally {
			if (app != null)
				app.invoke("Quit", wdDoNotSaveChanges);
		}
	}

	/**
	 * 通过Jacob插件调用Word应用程序，直接打印该文档
	 * @param toPrintWordFilePath 需要打印Word文档，全路径
	 */
	public static void printWordFile(String toPrintWordFilePath) {

		logger.info("启动Word...");
//		long start = System.currentTimeMillis();
		ActiveXComponent app = null;
		try {
			com.jacob.com.ComThread.InitSTA();
			app = new ActiveXComponent("Word.Application");
//			app.setProperty("Visible", false);
			Dispatch.put(app, "Visible", new com.jacob.com.Variant(false));//
			Dispatch docs = app.getProperty("Documents").toDispatch();
			logger.info("打开文档..." + toPrintWordFilePath);
			String[] sourceName = toPrintWordFilePath.split(",");
			for(int i=0;i<sourceName.length;i++){
				Dispatch doc = Dispatch.invoke(
						docs, 
						"Open", 
						Dispatch.Method,
	//					sourceName,
						new Object[] { sourceName[i] },
						new int[1]
						).toDispatch();
				Dispatch.call(doc, "PrintOut");
			}
			
		} catch (Exception e) {
			logger.error("========Error:批量打印错误："+e.getMessage());
		} finally {
//			if (app != null)
//				app.invoke("Quit", wdDoNotSaveChanges);
			app.invoke("Quit", new com.jacob.com.Variant[] {});
			com.jacob.com.ComThread.Release();
			logger.info("关闭Word打印进程。");
		}
	}
	public static void word_Print(String sourceFile) {

		logger.info("启动Word...");
//		long start = System.currentTimeMillis();
		ActiveXComponent app = null;
		try {
			com.jacob.com.ComThread.InitSTA();
			app = new ActiveXComponent("Word.Application");
			app.setProperty("Visible", false);
			Dispatch.put(app, "Visible", new com.jacob.com.Variant(false));//
			Dispatch docs = app.getProperty("Documents").toDispatch();
			System.out.println("打开文档..." + sourceFile);
			logger.info("打开文档..." + sourceFile);
			Dispatch doc = Dispatch.invoke(
					docs, 
					"Open", 
					Dispatch.Method,
					new Object[] { sourceFile },
					new int[1]
					).toDispatch();
			Dispatch.call(doc, "PrintOut");
			
			
		} catch (Exception e) {
			logger.error("========Error:批量打印错误："+e.getMessage());
			e.printStackTrace();
		} finally {
//			if (app != null)
//				app.invoke("Quit", wdDoNotSaveChanges);
			app.invoke("Quit", new com.jacob.com.Variant[] {});
			com.jacob.com.ComThread.Release();
			logger.info("关闭Word打印进程。");
		}
	}
}
